<?php
namespace app\logic;


use think\facade\Cache;

class Software extends Base
{
    // 初始化
    protected function initialize()
    {
        parent::initialize();
        $this->model = new \app\model\Software();
    }

    /**
     * 获取分页数据
     * @param array $where
     * @param string $field
     * @return mixed
     */
    public function getList($where = [], $field = "*")
    {
        $page = $where['page'] ?? 1;
        $limit = $where['limit'] ?? 10;

        // 删除无用参数
        if(isset($where['page'])) unset($where['page']);
        if(isset($where['limit'])) unset($where['limit']);

        $result = $this->model::withSearch(['id', 'name', 'status'], $where)
            ->field($field)
            ->order('id', 'desc')
            ->paginate([
                'page'      => $page,
                'list_rows' => $limit
            ]);

        return [config('status.success'), "ok", $result];
    }

    /**
     * 获取单条数据
     * @param array $where
     * @param string $field
     * @return mixed
     */
    public function getInfo($where = [], $field = "*")
    {
        return $this->model::where($where)
            ->field($field)
            ->find();
    }

    /**
     * 新增
     * @param $param
     * @return array
     */
    public function add($param)
    {
        $result = $this->model::create($param);
        // 清空缓存
        Cache::clear();
        if($result && $result->id) {
            return [config('status.success'), "新增成功"];
        }
        return [config('status.fail'), "新增失败"];
    }

    /**
     * 更新
     * @param $param
     * @return array
     */
    public function edit($param)
    {
        $result = $this->model::update($param);
        // 清空缓存
        Cache::clear();
        if($result && $result->id) {
            return [config('status.success'), "更新成功"];
        }
        return [config('status.fail'), "更新成功"];
    }

    /**
     * 删除
     * @param array $ids
     * @return array
     */
    public function delete($ids = [])
    {
        $soft_list = $this->model::with(['version'])
            ->where('id', 'in', $ids)
            ->select();
        // 关联删除版本数据
        $result = false;
        foreach ($soft_list as $soft) {
            $result = $soft->together(['version'])->delete();
        }
        // 清空缓存
        Cache::clear();
        if($result) {
            return [config('status.success'), "删除成功"];
        }
        return [config('status.fail'), "删除失败"];
    }

    /**
     * 修改状态
     * @param int $id
     * @return array
     */
    public function setStatus($id = 0)
    {
        $id = intval($id);
        $info = $this->model::where('id', $id)->find();
        if(!$info) {
            return [config('status.noData'), "请求修改的信息不存在"];
        }
        // 取反
        $info->status = !$info->status;
        $info->save();
        // 清空缓存
        Cache::clear();
        return [config('status.success'), "状态修改成功"];
    }

    /**
     * 获取版本更新信息
     * @param string $token
     * @return \think\response\Json
     */
    public function getNewVersion($token = "")
    {
        $cache_time = get_config('site', 'cache_time') ?: 24*60*60;
        // 过来特殊字符
        $token = strip_tags($token);
        $soft_info = $this->model::where('token', $token)
            ->where('status', 0)
            ->cache(true, $cache_time)
            ->field("id,token")
            ->find();
        if(!$soft_info) {
            return json(['code' => config('status.noData'), 'msg' => "数据不存在或隐藏"],404);
        }
        // 查询最新的版本
        $ver_info = $soft_info->version()
            ->where([
                'status' => '0',
                'sid' => $soft_info->id
            ])
            ->cache(true, $cache_time)
            ->order('id', 'desc')
            ->find();
        if(!$ver_info) {
            return json(['code' => config('status.noData'), 'msg' => "暂无可更新版本"], 404);
        }

        return json($ver_info->config);
    }

    /**
     * 获取更新配置地址
     * @param $id
     * @return array
     */
    public function getApiUrl($id)
    {
        $soft_info = $this->model::where('id', $id)
            ->field('id,name,token')
            ->find();
        if(!$soft_info) {
            return [config('status.noData'), "数据不存在请刷新"];
        }

        if(empty($soft_info->token)) {
            // 如果没有 token, 则立即生成
            $soft_info->token = md5($soft_info->id . $soft_info->name . time());
            $soft_info->save();
        }
        $api_url = rtrim(get_config('site', 'api_url') ?: request()->domain(), "/");
        $ret_url = $api_url ."/da-upver/" . $soft_info->token;
        return [config('status.success'), "ok", ['api_url' => $ret_url]];
    }
}